<template>
    <el-card v-loading="loading" class="certification_container">
        <template #header>
            <span class="card_header">
                实名信息
            </span>
        </template>
        <div class="certification_content">
            <div class="tip">
                <el-icon>
                    <InfoFilled />
                </el-icon>
                <span>完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步骤，建议提前实名认证。</span>
            </div>
        </div>
        <!-- 卡片身体的底部:认证成功的结构，认证未成功的结构 -->
        <el-descriptions v-if="userInfo.authStatus === 1" :column="1" :border="true">
            <el-descriptions-item label-align="center" :width="10">
                <template #label>
                    <div class="cell-item">
                        用户姓名
                    </div>
                </template>
                {{ userInfo?.name }}
            </el-descriptions-item>
            <el-descriptions-item label-align="center" :width="10">
                <template #label>
                    <div class="cell-item">
                        证件类型
                    </div>
                </template>
                {{ userInfo?.certificatesType === "10" ? "身份证" : "户口本" }}
            </el-descriptions-item>
            <el-descriptions-item label-align="center" :width="10">
                <template #label>
                    <div class="cell-item">
                        证件号码
                    </div>
                </template>
                {{ userInfo?.certificatesNo }}
            </el-descriptions-item>
        </el-descriptions>
        <!-- 用户未验证的结构 -->
        <el-form ref="form" :rules="rules" :model="params" v-if="userInfo.authStatus === 0" class="certification_form"
            label-width="74">
            <el-form-item label="用户姓名" prop="name">
                <el-input v-model="params.name" placeholder="请输入用户姓名"></el-input>
            </el-form-item>
            <el-form-item label="证件类型" prop="certificatesType">
                <el-select @change="changeCertificatesType" v-model="params.certificatesType" class="elSelect"
                    placeholder="请选择证件类型">
                    <el-option v-for="item in arrType" :value="item.value" :key="item.id" :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="certificatesNo">
                <el-input v-model="params.certificatesNo" placeholder="请输入证件号码"></el-input>
            </el-form-item>
            <el-form-item label="上传证件" prop="certificatesUrl">
                <!-- 
                    action:upload组件向服务器提交图片路径
                    limit:照片墙约束图片个数
                    on-exceed:超出约束数量的钩子
                -->
                <el-upload list-type="picture-card" ref="upload" :on-remove="handleRemove"
                    :on-preview="handlePictureCardPreview" :on-success="successhandler" :on-exceed="exceedhandler"
                    :limit="1" action="/api/oss/file/fileUpload?fileHost=userAuah">
                    <img class="upload-img" src="../../../../assets/images/auth_example.png" alt="auth_example">
                </el-upload>
                <el-dialog v-if="params.certificatesUrl" v-model="dialogVisible">
                    <img style="width: 100%;" :src="params.certificatesUrl" w-full alt="Preview Image" />
                </el-dialog>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="reset">重写</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { InfoFilled } from '@element-plus/icons-vue';
// 获取用户信息
import { reqUserCertation, reqUserInfo, reqCertationType } from '@/api/user';
import type { UserParams, CertationTypeResponseData, CertationArr, UserInfoResponseData } from '@/api/user/type';
// @ts-ignore
import type { FormRules } from 'element-plus'
// @ts-ignore
import { ElMessage } from 'element-plus';
// 存储用户信息
let userInfo = ref<any>({})
// 存储证件类型
let arrType = ref<CertationArr>([])
// 收集表单的数据
let params = reactive<UserParams>({
    certificatesNo: '',
    certificatesType: '',
    certificatesUrl: '',
    name: ''
});
// 照片墙的对话框
let dialogVisible = ref<boolean>(false)
// 拿到照片墙的实例
let upload = ref<any>()
// 获取form组件实例
let form = ref();
// 判断数据是否全部请求完毕
let loading = ref<boolean>(true);
// 自定义校验规则证件号码
const validatorCertificatesNo = (_: any, value: any, callBack: any) => {
    if (params.certificatesType === '20') {
        if (value.length == "9" && /\d{9}/.test(value)) {
            callBack();
        } else {
            callBack(new Error("请输入正确的九位户口本号码"));
        }
    } else if (params.certificatesType === '10') {
        if (value.length == "18" && /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
            callBack();
        } else {
            callBack(new Error("请输入正确的身份证"));
        }
    } else {
        callBack(new Error("请先选择证件的类型"));
    }
}
// 验证具体的某个字段 校验certificatesNo字段
const changeCertificatesType = () => {
    form.value.validateField('certificatesNo')
}
// 表单校验
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    certificatesType: [
        { required: true, message: '请选择证件类型', trigger: 'change' },
    ],
    certificatesNo: [
        { required: true, message: '请输入证件号码', trigger: 'blur' },
        { required: true, validator: validatorCertificatesNo }
    ],
    certificatesUrl: [
        { required: true, message: '请上传图片', trigger: 'change' },
    ],
})
onMounted(() => {
    // 获取用户信息的方法
    getUserInfo();
    // 获取证件类型的接口
    getType();
})
const getUserInfo = async () => {
    let { data, code }: UserInfoResponseData = await reqUserInfo();
    if (code === 200) {
        userInfo.value = data
    }
    loading.value = await false
}
const getType = async () => {
    let { data, code }: CertationTypeResponseData = await reqCertationType();
    if (code === 200) {
        arrType.value = data
    }
}
const submit = async () => {
    await form.value.validate(async (valid: any) => {
        if (valid) {
            let { code } = await reqUserCertation(params)
            if (code === 200) {
                ElMessage({
                    type: "success",
                    message: "认证成功",
                });
                getUserInfo();
            } else {
                ElMessage({
                    type: "error",
                    message: "认证失败",
                });
            }
        }
    })
}
// 超出数量的钩子
const exceedhandler = () => {
    ElMessage({
        type: "error",
        message: "只能上传一张图片",
    });
};
// 图片上传成功的钩子
const successhandler = (response: any) => {
    // 如果图片上传成功校验结果清除
    form.value.clearValidate('certificatesUrl');
    // 收集上传成功图片地址
    // response:上传图片请求服务器返回的数据
    // uploadFile上传文件对象
    params.certificatesUrl = response.data;
};
// 照片墙预览的钩子
const handlePictureCardPreview = () => {
    // 触发预览的钩子的时候，对话框显示
    dialogVisible.value = true;
};
// 照片墙删除图片的钩子
const handleRemove = () => {
    params.certificatesUrl = "";
};

// 重写按钮的回调
const reset = () => {
    // 重置该表单项，将其值重置为初始值，并移除校验结果
    form.value?.resetFields()
    // 清除文件上传列表
    upload.value.clearFiles();
};
</script>
<style scoped lang="scss">
.certification_container {
    .card_header {
        font-size: 24px;
    }

    .certification_content {
        .tip {
            display: flex;
            align-items: center;
            justify-content: center;
            color: lightcoral;
            margin-bottom: 16px;

            span {
                margin-left: 4px;
            }
        }
    }

    .certification_form {
        width: 60%;
        margin: 0 auto;

        .elSelect {
            width: 100%;
        }

        .upload-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }
}


@media (max-width:768px) {
    .certification_container {
        .card_header {
            font-size: 18px;
        }
    }

    .certification_content {
        .tip {
            margin-bottom: 10px !important;

            span {
                font-size: 14px;
            }
        }
    }

    .el-descriptions {
        .cell-item {
            white-space: nowrap;
        }
    }

    .certification_form {
        width: 100% !important;
    }
}
</style>